package com.zhongkun.datahome.web.controller.system;

import com.zhongkun.datahome.common.annotation.Log;
import com.zhongkun.datahome.common.core.controller.BaseController;
import com.zhongkun.datahome.common.core.domain.AjaxResult;
import com.zhongkun.datahome.common.core.page.TableDataInfo;
import com.zhongkun.datahome.common.enums.BusinessType;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import com.zhongkun.datahome.core.domain.SysConfig;
import com.zhongkun.datahome.core.service.ISysConfigService;
import com.zhongkun.datahome.service.domain.MiniProgramVisionSetting;
import com.zhongkun.datahome.service.req.cmd.system.MiniProgramDataSettingCmd;
import com.zhongkun.datahome.service.req.cmd.system.MiniProgramNodeSettingCmd;
import com.zhongkun.datahome.service.req.cmd.system.MiniProgramVisionSettingCmd;
import com.zhongkun.datahome.service.res.system.MiniProgramDataSettingVo;
import com.zhongkun.datahome.service.service.ISystemSettingService;
import com.zhongkun.datahome.service.utils.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 参数配置 信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController
{
    @Autowired
    private ISysConfigService configService;

    @Resource
    private ISystemSettingService systemSettingService;

    /**
     * 获取参数配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysConfig config)
    {
        startPage();
        List<SysConfig> list = configService.selectConfigList(config);
        return getDataTable(list);
    }

    @Log(title = "参数管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysConfig config)
    {
        List<SysConfig> list = configService.selectConfigList(config);
        ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
        util.exportExcel(response, list, "参数数据");
    }

    /**
     * 根据参数编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:config:query')")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable Long configId)
    {
        return success(configService.selectConfigById(configId));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    public AjaxResult getConfigKey(@PathVariable String configKey)
    {
        return success(configService.selectConfigByKey(configKey));
    }

    /**
     * 新增参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysConfig config)
    {
        if (!configService.checkConfigKeyUnique(config))
        {
            return error("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setCreateBy(getUsername());
        return toAjax(configService.insertConfig(config));
    }

    /**
     * 修改参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:edit')")
    @Log(title = "参数管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysConfig config)
    {
        if (!configService.checkConfigKeyUnique(config))
        {
            return error("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setUpdateBy(getUsername());
        return toAjax(configService.updateConfig(config));
    }

    /**
     * 删除参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "参数管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable Long[] configIds)
    {
        configService.deleteConfigByIds(configIds);
        return success();
    }

    /**
     * 刷新参数缓存
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache()
    {
        configService.resetConfigCache();
        return success();
    }

    @ApiOperation("添加小程序资料图标配置")
    @Log(title = "小程序配置", businessType = BusinessType.INSERT)
    @PostMapping("/mini/program/dataSetting")
    public AjaxResult addDataSetting(@RequestBody MiniProgramDataSettingCmd cmd) {
        cmd.setCreateBy(SecurityUtils.getTenantUserId());
        cmd.setTenantId(SecurityUtils.getTenantId());
        Boolean success = systemSettingService.addMiniProgramDataSetting(cmd);
        return success ? success() : error();
    }

    @ApiOperation("更新小程序资料图标配置")
    @Log(title = "小程序配置", businessType = BusinessType.UPDATE)
    @PutMapping("/mini/program/dataSetting")
    public AjaxResult updateDataSetting(@RequestBody MiniProgramDataSettingCmd cmd) {
        if (cmd.getLevel().equals(0)) {
            boolean hasChild = systemSettingService.queryHasChildDataSetting(cmd.getId());
            if (hasChild) {
                return error("含下级类型，不能改为末级类型。");
            }
        }
        cmd.setUpdateBy(SecurityUtils.getTenantUserId());
        cmd.setTenantId(SecurityUtils.getTenantId());
        Boolean success = systemSettingService.updateMiniProgramDataSetting(cmd);
        return success ? success() : error();
    }

    @ApiOperation("查询小程序资料图标tree")
    @GetMapping(value = "/roleDataSettingTreeSelect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", systemSettingService.getDataSettingtIdsByRoleId(roleId));
        ajax.put("menus", systemSettingService.getDataSettingTree());
        return ajax;
    }

    @ApiOperation("查询客户资产图标配置")
    @GetMapping("/list/customer/dataSetting")
    public AjaxResult listCustomerDataSetting() {
        List<MiniProgramDataSettingVo> miniProgramDataSettingVos = systemSettingService.listCustomerDataSetting();
        return success(miniProgramDataSettingVos);
    }

    @ApiOperation("查询小程序资料图标配置")
    @GetMapping("/mini/program/dataSetting")
    public AjaxResult queryMiniProgramDataSetting(Integer level) {
        List<MiniProgramDataSettingVo> miniProgramDataSettingVos = systemSettingService.queryMiniProgramDataSettingList(level);
        return success(miniProgramDataSettingVos);
    }

    @ApiOperation("删除小程序资料图标配置")
    @Log(title = "小程序配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/mini/program/dataSetting/{id}")
    public AjaxResult deleteMiniProgramDataSetting(@PathVariable("id") Long id) {
        boolean hasAssets = systemSettingService.queryMiniProgramDataSettingHasAssets(id);
        if (hasAssets) {
            return error("当前类型下有资料，不能删除");
        }
        boolean hasChild = systemSettingService.queryHasChildDataSetting(id);
        if (hasChild) {
            return error("含下级类型，不能删除");
        }
        Boolean success = systemSettingService.delMiniProgramDataSetting(id);
        return success ? success() : error();

    }

    @ApiOperation("添加小程序视觉配置")
    @Log(title = "小程序配置", businessType = BusinessType.INSERT)
    @PostMapping("/mini/program/visionSetting")
    public AjaxResult addVisionSetting(@RequestBody List<MiniProgramVisionSettingCmd> cmdList) {
        if (!cmdList.isEmpty()) {
            cmdList.forEach(cmd -> {
                cmd.setCreateBy(SecurityUtils.getTenantUserId());
                cmd.setTenantId(SecurityUtils.getTenantId());
            });
        }
        systemSettingService.batchAddMiniProgramVisionSetting(cmdList);
        return success();
    }

    @ApiOperation("查询小程序视觉配置")
    @GetMapping("/mini/program/visionSetting")
    public AjaxResult queryMiniProgramVisionSetting() {
        List<MiniProgramVisionSetting> miniProgramVisionSettings = systemSettingService.queryAllVisionSetting();
        return success(miniProgramVisionSettings);
    }

    @ApiOperation("保存小程序节点配置")
    @PostMapping("/mini/program/nodeSetting")
    @Log(title = "小程序节点配置", businessType = BusinessType.INSERT)
    public AjaxResult addNodeSetting(@RequestBody List<MiniProgramNodeSettingCmd> cmdList) {
        cmdList.forEach(cmd -> {
            cmd.setCreateBy(SecurityUtils.getTenantUserId());
            cmd.setUpdateBy(SecurityUtils.getTenantUserId());
            cmd.setTenantId(SecurityUtils.getTenantId());
        });
        systemSettingService.batchSaveMiniProgramNodeSetting(cmdList);
        return success();
    }

    @ApiOperation("删除小程序节点配置")
    @DeleteMapping("/mini/program/nodeSetting/{id}")
    @Log(title = "小程序节点配置", businessType = BusinessType.DELETE)
    public AjaxResult delNodeSetting(@PathVariable("id") Long id) {
        Boolean success = systemSettingService.delMiniProgramNodeSetting(id);
        return success ? success() : error();
    }

    @ApiOperation("查询小程序节点配置")
    @GetMapping("/mini/program/nodeSetting")
    public AjaxResult queryNodeSetting() {
        List<MiniProgramNodeSettingCmd> nodeSettings = systemSettingService.queryMiniProgramNodeSetting();
        return success(nodeSettings);
    }
}
